import Vue from 'vue'
import Vuex from 'vuex'
import authRouters from '../router/routers'
Vue.use(Vuex);
function hasPermission (permission, route) {
    if (route.meta && route.meta.permission) {
        if(permission.join(',').indexOf(route.meta.permission) != -1){
            return true
        }
        return false
    }
    return true
}
function filterAsyncRouter (routerMap, roles) {
    const accessedRouters = routerMap.filter(route => {
        if (hasPermission(roles, route)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, roles)
            }
            return true
        }
        return false
    })
    return accessedRouters
}
function getUserFirstRoute(route){
    if(route.children && route.children.length > 0){
        return getUserFirstRoute(route.children[0])
    }else{
        return route
    }
}
export default new Vuex.Store({
    state:{
        userInfo:{},
        permission:[],
        userRouters:[]
    },
    actions:{
        setUserInfo({commit},userInfo){
            commit('setUserInfo',userInfo)
        },
        setPermission({commit},perms){
            commit('setPermission',perms)
        },
        generateRoutes({commit,state}){
            const accessdRouters = filterAsyncRouter(authRouters,state.permission)
            state.userRouters = accessdRouters
        }
    },
    mutations:{
        setUserInfo(state,res){
            state.userInfo = res.user
            state.permission = res.perms
        },
        setUserRouters(state,routers){
            state.userRouters = routers;
        }
    },
    getters:{
        getPermission(state){
            return state.permission
        },
        isHasPermission:(state,getters) => (perm) =>{
            return state.permission.indexOf(perm) !== -1
        },
        getUserRouters(state){
            return state.userRouters
        },
        getUserGoRouter(state){
            if(state.userRouters.length == 0){
                return
            }
            const router = state.userRouters.find(item => item.path === '/')
            return getUserFirstRoute(router)
        },
        getUserInfo(state){
            return state.userInfo
        },
        getUserMenu(state){
            if(state.userRouters.length == 0){
                return
            }
            return state.userRouters.find(item => item.path === '/').children
        },
    }
})
